package com.epro.dx.activity;

import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.databinding.ActivityAlarmBinding;
import com.epro.dx.model.DateModel;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.JGUtils;
import com.epro.dx.widget.HoriScrollShimmerTV;
import com.romainpiel.shimmer.Shimmer;
import com.weipu.common.constants.Constant;
import com.weipu.common.facade.model.MessageModel;
import com.weipu.common.util.ImageUtils;
import com.weipu.common.util.StringUtil;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * 从收到物流推送周期后，同时手机处于锁屏的状态，则会跳转到这个界面来
 *
 * @author Zenglw
 * @version [1.0, 2017-6-23]
 */
public class AlarmActivity extends BaseFragmentActivity implements View.OnClickListener, HoriScrollShimmerTV.OnUnlockListener, HoriScrollShimmerTV.OnScrollListener {

    private LinearLayout rootView;
    private ActivityAlarmBinding binding;
    private HoriScrollShimmerTV shimmerTextView;
    private LinearLayout alarmTrackLayout;
    private TextView alarmTrackTitle;
    private DateModel dateModel;
    private Timer timer;
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { // 监听home键
//                String reason = intent.getStringExtra(SYSTEM_REASON);
                StringUtil.saveConfig(Constant.Global.IS_LOCK, false + "");
                if (!isFinishing()) {
                    finish();
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        //设置吧布局
        binding = DataBindingUtil.setContentView(this, R.layout.activity_alarm);
        //初始化控件
        initView();
        initEvent();
        //对背景进行高斯模糊
        blur();
        //初始化时间
        initDate();
        StringUtil.saveConfig(Constant.Global.IS_LOCK,true+"");
        registerReceiver(mHomeKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    /**
     * 初始化时间
     */
    private void initDate() {
        dateModel = new DateModel();
        binding.setDataInfo(dateModel);
        MessageModel messageModel = JGUtils.getInstance().getMessageModel();
        if (messageModel != null) {
            binding.alarmTrackStatus.setText(messageModel.getTitle());
        }
        startTime();
    }

    /**
     * 开始计时
     */
    private void startTime() {
        //开启定时器，计时,每隔一秒获取一次时间，显示在界面上
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Calendar calendar = Calendar.getInstance();
                dateModel.setHour(calendar.get(Calendar.HOUR_OF_DAY) + "");
                dateModel.setMonth(calendar.get(Calendar.MONTH) + 1 + "");
                dateModel.setDay(calendar.get(Calendar.DAY_OF_MONTH) + "");
                dateModel.setMinute(calendar.get(Calendar.MINUTE) + "");
                //月份从0开始
                if (dateModel.getMinute().length() <= 1) {
                    dateModel.setMinute("0" + dateModel.getMinute());
                }

                String weekDay = "";
                //一个星期的第几天，第一天是星期日
                switch (calendar.get(Calendar.DAY_OF_WEEK)) {

                    case 1:
                        weekDay = "星期天";
                        break;
                    case 2:
                        weekDay = "星期一";

                        break;
                    case 3:
                        weekDay = "星期二";
                        break;
                    case 4:
                        weekDay = "星期三";

                        break;
                    case 5:
                        weekDay = "星期四";

                        break;
                    case 6:
                        weekDay = "星期五";

                        break;
                    case 7:
                        weekDay = "星期六";
                        break;
                    default:

                        break;
                }
                dateModel.setWeekday(weekDay);
            }
        }, 0, 1000);
    }

    /**
     * 根据后台返回的数据获取分段获取内容
     *
     * @param title 后台返回的内容
     * @return 拆分拼接好的内容
     */
    private String getContent(String title) {
        String[] contentSplit = title.split("\\r\\n");
        int length = contentSplit.length;
        StringBuffer buffer = new StringBuffer();
        if (length == 4) {
            buffer.append(contentSplit[length - 3])
                    .append("\r\n")
                    .append(contentSplit[length - 2])
                    .append("\r\n")
                    .append(contentSplit[length - 1]);
        } else if (contentSplit.length == 3) {
            buffer.append(contentSplit[length - 2])
                    .append("\r\n")
                    .append(contentSplit[length - 1]);
        }
        return buffer.toString();
    }

    /**
     * 对页面背景进行高斯模糊，同时设置给根布局
     */
    private void blur() {
        // 需要详细说明一下，mScreenCount、getCurrentWorkspaceScreen()、mScreenWidth、mScreenHeight分别
//        //对应于Launcher中的桌面屏幕总数、当前屏幕下标、屏幕宽度、屏幕高度.
//        float step = 0;
//        // 计算出屏幕的偏移量
//        step = (bm.getWidth() - LauncherPreferenceModel.mScreenWidth)
//                / (LauncherPreferenceModel.mScreenCount - 1);
//        // 截取相应屏幕的Bitmap
//        Bitmap pbm = Bitmap.createBitmap(bm, (int) (mLauncher
//                        .getCurrentWorkspaceScreen() * step), 0,
//                (int) (LauncherPreferenceModel.mScreenWidth),
//                (int) (LauncherPreferenceModel.mScreenHeight));
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        // 获取当前壁纸
        Drawable wallpaperDrawable = wallpaperManager.getDrawable();
        // 将Drawable,转成Bitmap
        final Bitmap bm = ((BitmapDrawable) wallpaperDrawable).getBitmap();
        rootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                ImageUtils.blur(AlarmActivity.this, bm, rootView);
            }
        }, 10);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        rootView = (LinearLayout) binding.getRoot();
        alarmTrackLayout = binding.alarmTrackLayout;

        shimmerTextView = (HoriScrollShimmerTV) findViewById(R.id.shimmer_tv);

        //设置viewmore 箭头的大小
        Drawable drawable1 = getResources().getDrawable(R.drawable.arrow_right);
        drawable1.setBounds(0, 0, 15, 45);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        shimmerTextView.setCompoundDrawables(drawable1, null, null, null);//只放右边

        Shimmer shimmer = new Shimmer();
        shimmer.start(shimmerTextView);
    }

    private void initEvent() {
        alarmTrackLayout.setOnClickListener(this);
        shimmerTextView.setOnUnlockListener(this);
        shimmerTextView.setOnScrollListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.alarm_track_layout) {

            Intent toReceiverIntent = new Intent(JPushInterface.ACTION_NOTIFICATION_OPENED);
            sendBroadcast(toReceiverIntent);
            timer.cancel();
            finish();
        }
    }

    /**
     * 因为在清单文件中启动模式是singleInstance，这个方法是第二次+启动这个Activity时会回调的方法
     *
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        if (!pm.isScreenOn()) {
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire();
            wl.release();
        }
        //当另一条数据过来了，需要更新数据
        MessageModel messageModel = JGUtils.getInstance().getMessageModel();
        if (null != messageModel) {

            binding.alarmTrackStatus.setText(messageModel.getTitle() != null ? messageModel.getTitle() : "");

        }

    }

    /**
     * 设置状态栏透明
     */
    @Override
    protected void setStateColor() {
        ActivityUtil.setTranslucentState(this);
    }


    /**
     * 屏蔽物理返回键
     */
    @Override
    public void onBackPressed() {
    }

    /**
     * 当解锁屏幕时的回调
     */
    @Override
    public void onUnlock() {
        if (!isFinishing()) {
            timer.cancel();
            finish();
        }
    }

    /**
     * 当右划达到阈值的时候
     */
    @Override
    public void onRightScroll() {
        Intent toReceiverIntent = new Intent(JPushInterface.ACTION_NOTIFICATION_OPENED);
        sendBroadcast(toReceiverIntent);
        timer.cancel();
        finish();
    }

    /**
     * 当右划
     * @param distance
     */
    @Override
    public void onScroll(float distance) {
        binding.getRoot().setTranslationX(distance);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        StringUtil.saveConfig(Constant.Global.IS_LOCK, false + "");
        unregisterReceiver(mHomeKeyEventReceiver);
        timer = null;
    }
}
